package com.fotoloka.view;

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;

import javax.swing.JFrame;
import javax.swing.JPanel;

import com.fotoloka.services.WebCam;

@SuppressWarnings("serial")
public class ImagePanel2 extends JPanel {

	private Image img;

	private JFrame parent;

	private Thread runner = null;

	private boolean atualizar = true;

	private boolean centralizado = true;
	
	private WebCam webCam;

	public ImagePanel2(WebCam webCam, JFrame parent) {
		this.parent = parent;
		this.setBackground(Color.yellow);
		this.webCam = webCam;
	}

	public void iniciar() throws Exception {
		atualizar = true;
		runner = new Thread() {
			public void run() {
				while (atualizar) {
					atualizarImagem();
					Thread.yield();
				}
				runner = null;
			}
		};
		runner.start();
	}

	public void atualizarImagem() {
		img = webCam.getImage();
		this.repaint();
	}
	
	public void parar() {
		this.atualizar = false;
	}

	@Override
	public void paintComponent(Graphics g) {

		super.paintComponent(g);

		if (img == null) {
			return;
		}

		if (centralizado) {
			this.setBounds(0, 0, parent.getWidth(), parent.getHeight());

			int width = this.getWidth();
			int height = this.getHeight();

			Image imgAjustada = img.getScaledInstance(width, height,
					Image.SCALE_AREA_AVERAGING);

			g.drawImage(imgAjustada, 0, 0, this);
		} else {
			g.drawImage(img, 0, 0, this);
		}

	}
}
